package com.ojoin.trade.common.spring;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.collections.MapUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;

import com.ojoin.trade.common.jedis.support.BinaryJedisCmd;

/**
 * 支持spring-3.1 的cache注解
 * 上下文事物支持
 */
public class RedisCacheManager extends AbstractTransactionSupportingCacheManager {
  private int expiration = 0;
  private BinaryJedisCmd redis;
  private Map<String,Integer> initCache;

  public Map<String, Integer> getInitCache() {
	return initCache;
}

public void setInitCache(Map<String, Integer> initCache) {
	this.initCache = initCache;
}

public RedisCacheManager(int expiration, BinaryJedisCmd redis) {
    this.expiration = expiration;
    this.redis = redis;
  }

  public int getExpiration() {
    return expiration;
  }

  public void setExpiration(int expiration) {
    this.expiration = expiration;
  }

  	@Override
	public Cache getCache(String name) {
		Cache cache = super.getCache(name);
			if (null == cache) {
				cache = new RedisCache(name, expiration, redis);
				addCache(cache);
			}
		return cache;
	}

	@Override
	protected Collection<? extends Cache> loadCaches() {
		Collection<RedisCache> caches=null;
		if(MapUtils.isNotEmpty(initCache)){
			caches = new LinkedHashSet<RedisCache>(initCache.size());
			Set<Entry<String,Integer>> set=initCache.entrySet();
			for (Entry<String,Integer> entry : set) {
				caches.add(new RedisCache(entry.getKey(), entry.getValue(), redis));
			}
		}
		return caches;
	}
  
}
